package com.bpm.example.event.message;

import com.bpm.common.util.FlowableEngineUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.eventsubscription.api.EventSubscription;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.junit.Test;

import java.util.List;

/**
 * 消息边界事件示例流程
 */
@Slf4j
public class RunMessageBoundaryEventProcessDemo extends FlowableEngineUtil {
    @Test
    public void runSignalBoundaryEventProcessDemo() throws Exception {
        //加载Flowable配置文件并初始化流程引擎及服务
        initFlowableEngineAndServices("flowable.cfg.xml");
        //部署流程
        ProcessDefinition procDef
                = deployResource("processes/MessageBoundaryEventProcess.bpmn20.xml");

        //启动流程实例,进入任务一
        ProcessInstance procInst = runtimeService.startProcessInstanceById(procDef.getId());

        EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery()
                .processInstanceId(procInst.getId())
                .eventName("message2")
                .singleResult();
        //发送了消息
        runtimeService.messageEventReceived("message2",eventSubscription.getExecutionId());

        TaskQuery taskQuery = taskService.createTaskQuery()
                .processInstanceId(procInst.getId());
        //查询并完成任务一
        Task firstTask = taskQuery.singleResult();
        log.info("第一个用户任务为：{}", firstTask.getName());
        taskService.complete(firstTask.getId());

        //进入任务二
        EventSubscription eventSubscription2 = runtimeService.createEventSubscriptionQuery()
                .processInstanceId(procInst.getId())
                .eventName("message3")
                .singleResult();
        //发送了消息
        runtimeService.messageEventReceived("message3",eventSubscription2.getExecutionId());

        //查询并完成任务
        Task task = taskQuery.singleResult();
        log.info("第2个用户任务为：{}", task.getName());
        taskService.complete(task.getId());

    }
}
